<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/27
 * Time: 16:08
 */
namespace app\api\service;

use app\lib\enum\ScopeEnum;
use app\lib\exception\TokenException;
use app\lib\exception\WeChatException;
use think\Exception;
use app\api\model\User as UserModel;

class UserToken extends Token{
    protected $code;
    protected $wx_app_id;
    protected $wx_app_secret;
    protected $wx_login_url;

    public function __construct($code){
        $this->code = $code;
        $this->wx_app_id = config('wx.app_id');
        $this->wx_app_secret = config('wx.app_secret');
        $this->wx_login_url = sprintf(config('wx.login_url'),$this->wx_app_id,$this->wx_app_secret,$this->code);
    }

    public function get(){
        $result = curl_get($this->wx_login_url);
        $wxResult = json_decode($result,true);
        if(empty($wxResult)){
            throw new Exception('获取session_key及openid时异常');
        }else{
            if(array_key_exists('errcode',$wxResult)){
                throw new WeChatException([
                    'msg'=>$wxResult['errmsg'],
                    'errorCode'=>$wxResult['errcode']
                ]);
            }else{
               return $this->granToken($wxResult);
            }
        }
    }

    private function granToken($wxResult){
//        拿到openid
//        判断数据库中是否已经存在
//        存在不做处理，不存在就新增一条user记录
//        生成令牌，缓存数据，写入缓存
//        把令牌返回到客户端
        $openId = $wxResult['openid'];
        $user = UserModel::getByOpenId($openId);
        if($user){
            $uid = $user->id;
        }else{
            $user = UserModel::create(['openid'=>$openId]);
            $uid = $user->id;
        }
        $cachedValue = $wxResult;
        $cachedValue['uid'] = $uid;
        $cachedValue['scope'] = ScopeEnum::User;
//        $cachedValue['scope'] = 16;
        $key = self::generateToken(); //生成令牌
        $value = json_encode($cachedValue);
        $expire_in = config('wx.token_expire_in');
        $request = cache($key,$value,$expire_in);
        if(empty($request)){
            throw new TokenException([
                'msg'=>'服务器缓存异常',
                'errorCode'=>'10005'
            ]);
        }
        return $key;
    }

}